package org.cncy;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;

import java.io.Serializable;

/**
 * 拉取策略
 */
public class I5001JavaSampler extends AbstractJavaSamplerClient implements Serializable {

    private static final Logger log = LoggerFactory.getLogger(I5001JavaSampler.class);
    private static final long serialVersionUID = 240l;
    private final static String URL = "url";

    public I5001JavaSampler() {
        log.debug(Utils.whoAmI(this) + "\tConstruct");
    }

    @Override
    public Arguments getDefaultParameters() {
        Arguments arguments = new Arguments();
        arguments.setComment("拉取策略接口");
        arguments.addArgument("ClientUID", "");
        arguments.addArgument(URL, "");
        return arguments;
    }

    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {

        SampleResult results = new SampleResult();
        //返回请求值，体现在jmeter查看结果数请求里面
        String ClientUID = javaSamplerContext.getParameter("ClientUID");
        String url = javaSamplerContext.getParameter(URL);
        log.debug("clientUID = {}, url = {}", ClientUID, url);
        String body = "{\"header\":{\"version\":\"v2\"},\"body\":{\"maxCmdNum\":0,\"udid\":\"" + ClientUID + "\"}}";
        log.debug("requestBody = {}", body);
        results.setSamplerData(body);
        results.sampleStart();
        try {
            byte[] requestBody = HttpsJsonUtil.getJsonRequestByte(5001, body);
           // results.setSentBytes(requestBody.length);
            byte[] bytes =
                    HttpsUtils.doPost(url, requestBody);
            // byte[] bytes1 = Utils.interceptBody(bytes);
            results.setSuccessful(true);//这里决定测试用例成功还是失败
            //设置返回信息
            results.setResponseCode("200");
            results.setResponseMessage("成功测试");
            //results.setSampleLabel("获取策略");
            //返回结果
            results.setResponseData(new String(Utils.interceptBody(bytes)), "utf-8");
        } catch (Exception e) {
            log.error("Exception = {}", e);
            results.setSuccessful(false);
        } finally {
            // Record end time and populate the results.
            results.sampleEnd();
        }
        if (log.isDebugEnabled()) {
            log.debug(Utils.whoAmI(this) + "\tI5001JavaSample" + "\tTime:\t" + results.getTime());
        }
        return results;
    }


}
